package com.fm.magic.net.proxy;

import com.fm.base.json.JsonObject;
import com.fm.base.net.proxy.HttpProxy;
import com.fm.base.util.Pair;
import com.fm.commons.net.http.HttpClient;
import com.fm.commons.net.http.HttpRequest;
import com.fm.commons.net.http.HttpResponse;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

public class HttpProxyAssessor implements AutoCloseable {
    interface AssessorTask {
        String getName();

        Pair<HttpRequest, JsonObject> getRequest(HttpProxy proxy);

        boolean check(JsonObject metaData, HttpResponse response);
    }

    protected HttpClient client;
    protected List<AssessorTask> assessorTasks = new LinkedList<>();

    public HttpProxyAssessor(int maxThread) {
        client = new HttpClient(maxThread);
    }

    public void addAssessTask(AssessorTask assessor) {
        assessorTasks.add(assessor);
    }

    public Map<String, Long> assessAllTasks(HttpProxy proxy) {
        Map<String, Long> result = new HashMap<>();
        for (AssessorTask assessorTask : assessorTasks) {
            Pair<HttpRequest, JsonObject> requestPair = assessorTask.getRequest(proxy);
            HttpRequest request = requestPair.getLeft();
            JsonObject metaData = requestPair.getRight();
            long time = -System.currentTimeMillis();
            HttpResponse response = client.send(request);
            time += System.currentTimeMillis();
            if (assessorTask.check(metaData, response)) {
                result.put(assessorTask.getName(), time);
            }
        }
        return result;
    }

    @Override
    public void close() {
        client.close();
    }
}
